package utils

import (
	"encoding/json"
	"github.com/dpwgc/kapokmq-go-client/conf"
	"github.com/dpwgc/kapokmq-go-client/conn"
	"github.com/spf13/viper"
	"local/models"
)

// InitMQ 与Kapokmq消息队列建立连接
func InitMQ() {
	//创建生产者模板
	producer := conf.Producer{
		MqAddr:     viper.GetString("kapokmq.mqAddr"),     //消息队列服务IP地址
		MqPort:     viper.GetString("kapokmq.mqPort"),     //消息队列服务端口号
		MqProtocol: viper.GetString("kapokmq.mqProtocol"), //消息队列连接协议：ws/wss
		Topic:      viper.GetString("kapokmq.topic"),      //生产者订阅的主题
		ProducerId: viper.GetString("kapokmq.producerId"), //生产者Id
		SecretKey:  viper.GetString("kapokmq.secretKey"),  //消息队列访问密钥
	}

	//生产者与消息队列建立连接
	err := conn.NewProducerConn(producer)
	if err != nil {
		panic(err)
	}

	//创建消费者模板
	consumer := conf.Consumer{
		MqAddr:     viper.GetString("kapokmq.mqAddr"),     //消息队列服务IP地址
		MqPort:     viper.GetString("kapokmq.mqPort"),     //消息队列服务端口号
		MqProtocol: viper.GetString("kapokmq.mqProtocol"), //消息队列连接协议：ws/wss
		Topic:      viper.GetString("kapokmq.topic"),      //消费者订阅的主题
		ConsumerId: viper.GetString("kapokmq.consumerId"), //消费者Id
		SecretKey:  viper.GetString("kapokmq.secretKey"),  //消息队列访问密钥
	}

	//消费者与消息队列建立连接
	err = conn.NewConsumerConn(consumer)
	if err != nil {
		panic(err)
	}
}

// GetMsg 从消息队列中获取消息
func GetMsg() (models.UserMessage, bool) {

	//接收消息队列推送过来的消息mqMsg
	mqMsg, isOk := conn.ConsumerReceive()

	//取出消息队列的消息主体，将其解析到models.UserMessage
	userMessage := models.UserMessage{}
	if isOk {
		err := json.Unmarshal([]byte(mqMsg.MessageData), &userMessage)
		if err != nil {
			return userMessage, false
		}
		return userMessage, true
	}
	return userMessage, false
}
